<template>
    <el-table
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="id"
        :max-height="tableHeight"
        @cell-dblclick="onUpdate"
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :type="col.type"
                :sortable="col.sortable"
            >
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-button class="btn" type="primary"  @click="onAdd"
            >增加功能</el-button
        >
        <el-button class="btn" type="primary"  @click="onDelete"
            >删除功能</el-button
        >
        <el-button class="btn" type="primary"  @click="onQuery"
            >查询</el-button
        >
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>

    <el-dialog
        v-model="dialogUpdateVisible"
        title="功能维护"
        draggable
        destroy-on-close
    >
        <Action
            :data="paramAction"
            @create="onNewAction"
            @update="onUpdateAction"
            @close="onCloseDialog"
        >
        </Action>
    </el-dialog>

    <el-dialog
        v-model="dialogQueryVisible"
        title="功能查询"
        draggable
        destroy-on-close
    >
        <QueryForm
            :queryItems="queryItems"
            @yh-closedialog="onCloseDialog"
        ></QueryForm>
    </el-dialog>
</template>
<script setup lang="ts" name="SysActions">
import { ref, reactive, onMounted, ComputedRef, computed } from 'vue';
import { ElMessage, ElMessageBox, ElTable } from 'element-plus';
// import { Delete, Plus, Search } from '@element-plus/icons-vue';
import {
    isEmpty,
    forEach,
    findIndex,
    forEachRight,
    includes,
    omit,
} from 'lodash';

import { ActionModel } from '@/common/types/model';
import {
    tableColumnDefault,
    tableDefaultAttribute,
    useTableInfo,
    useTableHeightInfo
} from '@/hooks/useTable';
import type { QueryItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import { tableMaxHeightAdjust } from '@/common/const';
import Action from './Action.vue';

const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = reactive<Array<ActionModel>>([]);
// let tableHeight = ref(0);

const dialogUpdateVisible = ref(false);
const dialogQueryVisible = ref(false);

let queryWhere = {};
let paramAction: ActionModel | undefined;

const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'label',
        label: '功能名称',
        sortable: true,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'url',
        label: 'url',
        sortable: true,
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'remark',
        label: '备注',
        sortable: false,
    },
]);


const onRefresh = async () => {
    const req = new Request('功能查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.length = 0;
    // tableData.value = [];
    if (!isEmpty(r.obj)) {
        forEach(r.obj, (value) => {
            tableData.push(value);
        });
    }
    
};
const tableHeight = ref(100);

const { currentPage, orders, pageSize, totalnum, handleSizeChange, handleCurrentChange, handleSortChange } = useTableInfo(onRefresh);
onMounted(() => {
    // onRefresh();
    tableHeight.value = window.innerHeight - tableMaxHeightAdjust;
    // useTableHeightInfo(tableRef, tableHeight);
    // tableHeight.value = window.innerHeight - Math.ceil(tableRef.value?.$el.getBoundingClientRect().bottom ) + tableMaxHeightAdjust;
});

const onUpdate = (row: any, column: any, cell: any, event: any) => {
    paramAction = row;
    // console.log(paramUser);
    dialogUpdateVisible.value = true;
};
const onCloseDialog = async (arg?: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};
const onAdd = () => {
    // console.log(tableRef.value?.rowKey);
    // return;
    paramAction = undefined;
    dialogUpdateVisible.value = true;
};

const onDelete = async () => {
    const rows: Array<ActionModel> = tableRef.value?.getSelectionRows() || [];
    const names = Array<string>();
    const ids = Array<number>();
    forEach(rows, (v: ActionModel) => {
        names.push(v.label as string);
        ids.push(v.id as number);
    });
    const msg = names.join(',     ');
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认删除如下功能', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('功能删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(tableData, (v: ActionModel, i: number) => {
                if (includes(ids, v.id)) {
                    tableData.splice(i, 1);
                }
            });
        }
    }
};
const onNewAction = (data: ActionModel) => {
    tableData.unshift(data);
};
const onUpdateAction = (data: ActionModel) => {
    const i = findIndex(tableData, (o) => {
        return o.id === data.id;
    });
    if (i > -1) {
        Object.assign(tableData[i], omit(data, ['id']));
    } else {
        ElMessage.error('修改失败');
    }

    // tableData[i] = data;
};
const onQuery = () => {
    dialogQueryVisible.value = true;
};
const queryItems: Array<QueryItem> = [
    {
        fieldCod: 'label',
        fieldName: '功能名称',
        fieldType: 'string',
    },
    {
        fieldCod: 'url',
        fieldName: 'url',
        fieldType: 'string',
    },
    {
        fieldCod: 'remark',
        fieldName: '备注',
        fieldType: 'string',
    },
];
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
